<template>
  <div v-loading.fullscreen.lock="isLoading">
    <div class="wrapper-form">
      <el-form inline>
        <el-form-item label="统计时段">
          <el-date-picker
            v-model="range"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="起始日期"
            end-placeholder="截止日期"
            style="max-width: 240px"
          />
        </el-form-item>
        <el-form-item label="">
          <el-checkbox label="对比" v-model="isCompare" />
        </el-form-item>
        <el-form-item label="对比时段" v-show="isCompare">
          <el-date-picker
            v-model="range2"
            type="daterange"
            unlink-panels
            range-separator="至"
            start-placeholder="起始日期"
            end-placeholder="截止日期"
            style="max-width: 240px"
          />
        </el-form-item>
        <el-form-item label="">
          <el-text>数据优化：不计入小时数</el-text>
          <el-input-number v-model="hourDispose" :min="0" :max="50" />
          <el-text>以下的人数，0表示不优化</el-text>
        </el-form-item>
        <el-form-item label="">
          <el-divider direction="vertical" />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="handle" style="min-width: 120px">
            <el-icon><Histogram /></el-icon>
            <span>统计</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="wrapper-content" v-if="resultData != null && !isLoading">
      <div class="content-title">统计结果</div>
      <div class="content-extra">
        <div>
          统计时段：{{ responseData[0].startTime }} ~
          {{ responseData[0].endTime }}
        </div>
        <div v-if="responseData.length > 1" style="padding-top: 4px">
          对比时段：{{ responseData[1].startTime }} ~
          {{ responseData[1].endTime }}
        </div>
      </div>
      <!-- <el-divider /> -->
      <div class="content-data">
        <div class="line" v-for="(data, key, index) in resultData">
          <span class="line-label">{{ data.label }}</span>
          <span class="line-value-group">
            <span class="line-value2" v-if="data.value2 !== null">{{
              data.value2
            }}</span>
            <span class="line-split" v-if="data.value2 !== null">
              <!-- <el-icon><ArrowRightBold /></el-icon> -->
              <el-icon><DArrowRight /></el-icon>
            </span>
            <span class="line-value">{{ data.value }}</span>
          </span>
          <span
            class="line-growth line-growth-decrease"
            v-if="data.growth !== null && data.growth < 0"
          >
            <!-- <el-icon><Bottom /></el-icon> -->
            <el-icon><CaretBottom /></el-icon>
            <span class="line-growth-value">
              <span>{{ -data.growth }}</span>
              <span class="line-growth-percentage">%</span>
            </span>
          </span>
          <span
            class="line-growth"
            v-else-if="data.growth !== null && data.growth === 0"
          >
            <el-icon><span style="width: 20px; height: 20px"></span></el-icon>
            <span class="line-growth-value">
              <span>{{ data.growth }}</span>
              <span class="line-growth-percentage">%</span>
            </span>
          </span>
          <span
            class="line-growth line-growth-increase"
            v-else-if="data.growth !== null && data.growth > 0"
          >
            <!-- <el-icon><Top /></el-icon> -->
            <el-icon><CaretTop /></el-icon>
            <span class="line-growth-value">
              <span>{{ data.growth }}</span>
              <span class="line-growth-percentage">%</span>
            </span>
          </span>
        </div>
      </div>
    </div>
    <div class="wrapper-content" v-else>
      <el-empty />
    </div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";

const range = ref([new Date(), new Date()]);
const range2 = ref([new Date(), new Date()]);
const isCompare = ref(false);
const hourDispose = ref(0);

const isLoading = ref(false);
const responseData = ref();
const resultData = ref();

const handle = () => {
  responseData.value = new Array();
  const data = new Array();
  isLoading.value = true;
  axios
    .post("api/utils_general_report.php", {
      startTime: dayjs(range.value[0]).format("YYYY-MM-DD") + " 00:00:00",
      endTime: dayjs(range.value[1]).format("YYYY-MM-DD") + " 23:59:59",
      hourDispose: hourDispose.value,
    })
    .then((response) => {
      data.push(response.data);
      // console.log(response);
      if (isCompare.value) {
        axios
          .post("api/utils_general_report.php", {
            startTime:
              dayjs(range2.value[0]).format("YYYY-MM-DD") + " 00:00:00",
            endTime: dayjs(range2.value[1]).format("YYYY-MM-DD") + " 23:59:59",
            hourDispose: hourDispose.value,
          })
          .then((response2) => {
            // console.log(response2);
            data.push(response2.data);
            responseData.value = data;
            fetchData(data);
            isLoading.value = false;
            ElNotification({
              type: "success",
              duration: 2000,
              title: "已完成",
            });
          })
          .catch((error2) => {
            ElNotification({
              title: "Error",
              message: error2.message,
              type: "error",
              duration: 5000,
            });
          });
      } else {
        responseData.value = data;
        fetchData(data);
        isLoading.value = false;
        ElNotification({ type: "success", duration: 2000, title: "已完成" });
      }
    })
    .catch((error) => {
      ElNotification({
        title: "Error",
        message: error.message,
        type: "error",
        duration: 5000,
      });
    });
};

const compare = (val, val2) => {
  return Math.round(((val - val2) / val2) * 100);
};

const fetchData = (data) => {
  resultData.value = null;
  let result = {};
  let type = data.length;
  if (!type) return null;
  //
  result["flowZUUU"] = { label: "双流架次" };
  result["flowZUUU"]["value"] = type >= 1 ? data[0].flow.ZUUU : null;
  result["flowZUUU"]["value2"] = type == 2 ? data[1].flow.ZUUU : null;
  result["flowZUUU"]["growth"] =
    type == 2 ? compare(data[0].flow.ZUUU, data[1].flow.ZUUU) : null;
  // ====================
  result["flowZUTF"] = { label: "天府架次" };
  result["flowZUTF"]["value"] = type >= 1 ? data[0].flow.ZUTF : null;
  result["flowZUTF"]["value2"] = type == 2 ? data[1].flow.ZUTF : null;
  result["flowZUTF"]["growth"] =
    type == 2 ? compare(data[0].flow.ZUTF, data[1].flow.ZUTF) : null;
  // ====================
  result["flowMisc"] = { label: "绵阳及飞越架次" };
  result["flowMisc"]["value"] = type >= 1 ? data[0].flow.Misc : null;
  result["flowMisc"]["value2"] = type == 2 ? data[1].flow.Misc : null;
  result["flowMisc"]["growth"] =
    type == 2 ? compare(data[0].flow.Misc, data[1].flow.Misc) : null;
  // ====================
  result["flowTotal"] = { label: "终端架次" };
  result["flowTotal"]["value"] = type >= 1 ? data[0].flow.Total : null;
  result["flowTotal"]["value2"] = type == 2 ? data[1].flow.Total : null;
  result["flowTotal"]["growth"] =
    type == 2 ? compare(data[0].flow.Total, data[1].flow.Total) : null;
  // ====================
  result["sectorHours"] = { label: "扇区总时长" };
  result["sectorHours"]["value"] =
    type >= 1 ? data[0].sector.sectorHours : null;
  result["sectorHours"]["value2"] =
    type == 2 ? data[1].sector.sectorHours : null;
  result["sectorHours"]["growth"] =
    type == 2
      ? compare(data[0].sector.sectorHours, data[1].sector.sectorHours)
      : null;
  // ====================
  result["totalHours"] = { label: "打卡总时长" };
  result["totalHours"]["value"] = type >= 1 ? data[0].hour.totalHours : null;
  result["totalHours"]["value2"] = type == 2 ? data[1].hour.totalHours : null;
  result["totalHours"]["growth"] =
    type == 2
      ? compare(data[0].hour.totalHours, data[1].hour.totalHours)
      : null;
  // ====================
  result["memberCount"] = { label: "打卡总人数" };
  result["memberCount"]["value"] = type >= 1 ? data[0].hour.memberCount : null;
  result["memberCount"]["value2"] = type == 2 ? data[1].hour.memberCount : null;
  result["memberCount"]["growth"] =
    type == 2
      ? compare(data[0].hour.memberCount, data[1].hour.memberCount)
      : null;
  // ====================
  result["hoursPerCapita"] = { label: "人均打卡时长" };
  result["hoursPerCapita"]["value"] =
    type >= 1 ? data[0].hour.hoursPerCapita : null;
  result["hoursPerCapita"]["value2"] =
    type == 2 ? data[1].hour.hoursPerCapita : null;
  result["hoursPerCapita"]["growth"] =
    type == 2
      ? compare(data[0].hour.hoursPerCapita, data[1].hour.hoursPerCapita)
      : null;
  // ====================
  result["flowPerCapita"] = { label: "人均指挥架次" };
  result["flowPerCapita"]["value"] =
    type >= 1 ? data[0].capitaFlow.flowPerCapita : null;
  result["flowPerCapita"]["value2"] =
    type == 2 ? data[1].capitaFlow.flowPerCapita : null;
  result["flowPerCapita"]["growth"] =
    type == 2
      ? compare(
          data[0].capitaFlow.flowPerCapita,
          data[1].capitaFlow.flowPerCapita
        )
      : null;

  // ====================
  // ↓↓↓优化过的数据↓↓↓
  // ====================
  if (hourDispose.value > 0) {
    result["memberCount"] = { label: "打卡总人数（已优化）" };
    result["memberCount"]["value"] =
      type >= 1 ? data[0].hour.memberCount2 : null;
    result["memberCount"]["value2"] =
      type == 2 ? data[1].hour.memberCount2 : null;
    result["memberCount"]["growth"] =
      type == 2
        ? compare(data[0].hour.memberCount2, data[1].hour.memberCount2)
        : null;
    // ====================
    result["hoursPerCapita"] = { label: "人均打卡时长（已优化）" };
    result["hoursPerCapita"]["value"] =
      type >= 1 ? data[0].hour.hoursPerCapita2 : null;
    result["hoursPerCapita"]["value2"] =
      type == 2 ? data[1].hour.hoursPerCapita2 : null;
    result["hoursPerCapita"]["growth"] =
      type == 2
        ? compare(data[0].hour.hoursPerCapita2, data[1].hour.hoursPerCapita2)
        : null;
    // ====================
    result["flowPerCapita"] = { label: "人均指挥架次（已优化）" };
    result["flowPerCapita"]["value"] =
      type >= 1 ? data[0].capitaFlow2.flowPerCapita : null;
    result["flowPerCapita"]["value2"] =
      type == 2 ? data[1].capitaFlow2.flowPerCapita : null;
    result["flowPerCapita"]["growth"] =
      type == 2
        ? compare(
            data[0].capitaFlow2.flowPerCapita,
            data[1].capitaFlow2.flowPerCapita
          )
        : null;
  }
  // ====================
  // ↑↑↑优化过的数据↑↑↑
  // ====================
  result["flowPerSector"] = { label: "扇区时均通行量" };
  result["flowPerSector"]["value"] =
    type >= 1 ? data[0].sectorFlow.flowPerSector : null;
  result["flowPerSector"]["value2"] =
    type == 2 ? data[1].sectorFlow.flowPerSector : null;
  result["flowPerSector"]["growth"] =
    type == 2
      ? compare(
          data[0].sectorFlow.flowPerSector,
          data[1].sectorFlow.flowPerSector
        )
      : null;
  // ====================
  resultData.value = result;
  return result;
};
</script>

<style scoped>
.wrapper-form {
  padding: 2em;
}

.wrapper-content {
  padding: 1em;
}

.content-title {
  font-size: 2em;
  color: var(--el-text-color-primary);
  padding-bottom: 14px;
  font-weight: bolder;
  text-align: center;
}

.content-extra {
  color: var(--el-text-color-secondary);
  padding-bottom: 14px;
  text-align: center;
}

.content-data {
  padding: 2em 1em;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.line {
  max-width: 800px;
  width: 100%;
  height: 48px;
  /* max-width: 640px; */
  display: flex;
  align-items: center;
  justify-content: space-between;
  /* padding: 0 max(2em, 10vw); */
  border-bottom: 1px dotted var(--el-color-info-light-5);
  opacity: 0.8;
  transition: all 0.3s ease-in-out;
  cursor: pointer;
  text-align: center;
}

.line:first-child {
  border-top: 1px dotted var(--el-color-info-light-5);
}

.line:hover {
  background-color: var(--el-color-info-light-9);
  opacity: 1;
  transform: scale(1.03);
}

.line-label {
  min-width: 200px;
  /* font-size: 1.1em; */
  color: var(--el-text-color-primary);
}
.line-value-group {
  min-width: 240px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.line-value {
  color: var(--el-text-color-primary);
  font-weight: bold;
  font-size: 1.5em;
  width: 120px;
}
.line-split {
  /* padding: 0 1em; */
  width: 40px;
  color: var(--el-text-color-placeholder);
}
.line-value2 {
  color: var(--el-text-color-placeholder);
  width: 100px;
  font-size: 1.25em;
}
.line-growth {
  width: 120px;
  font-size: 1.25em;
  color: var(--el-text-color-placeholder);
  display: flex;
  align-items: center;
}

.line-growth-value {
  display: flex;
  align-items: end;
  padding-left: 4px;
}

.line-growth-increase {
  color: var(--el-color-danger-dark-2);
}

.line-growth-decrease {
  color: var(--el-color-success-dark-2);
}
.line-growth-percentage {
  padding-left: 4px;
  font-size: 0.5em;
}
</style>
